/*
 * @Author: 码农 2646995216@qq.com
 * @Date: 2025-03-19 15:40:12
 * @LastEditors: 码农 2646995216@qq.com
 * @LastEditTime: 2025-03-19 22:01:33
 * @FilePath: /netcomputer/clientmain.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "socket.hpp"
#include <ctime>
#include "protocol.hpp"
#include <unistd.h>
#include <assert.h>

int main(int args, char *argv[])
{
	//端口号和ip地址
	string ip = argv[1];
	uint16_t port = stoi(argv[2]);

	//创建套接字
	Sock sockfd;
	sockfd.Socket();

	//连接服务器
	bool n = sockfd.Connect(ip, port);
	if (!n)
		return 1;

	//随机数种子
	srand(time(nullptr));
	string opers = "+-*/%=";

	int count = 1;
	string buffer_stream;//定义在这，是为了防止客户端给服务器发送的报文不完整
	while (count <= 5)
	{
		cout<<"=========================第"<<count<<"次==========================="<<endl;
		int x = rand() % 10;
		usleep(1005);
		int y = rand() % 5;
		usleep(1500);
		char op = opers[rand() % opers.size()];

		Request req(x, y, op);
		req.PrintData();//打印请求

		string package;
		req.Serialization(package);//将请求序列化

		package = AddMasthead(package);//给请求添加报头
	    cout<<"请求的格式: "<<package<<endl;
		int i=write(sockfd.Getlistensockfd(), package.c_str(), package.size());//将请求写给服务器

		char buffer[1024];
		int m = read(sockfd.Getlistensockfd(), buffer, sizeof(buffer));//服务器处理完后，将回应，返回给客户端
		if (m > 0)
		{
			buffer[m] = 0;
			buffer_stream += buffer;
            cout<<"回应后的格式：" <<buffer_stream << endl;

			string content;
			bool a = DeleteMasthead(buffer_stream, content);//拿到处理结果后，去掉结果的报头
			assert(a);

			Response reaq;
			bool b = reaq.desocialization(content);//将结果反序列化，并且将结果存入Response类中
			assert(b);

			reaq.PrintfData();//打印结果
		}
		else
		{
			cout << "read false" << endl;
		}
		cout << "================================================" << endl;
		sleep(1);
		count++;
	}
	sockfd.Close();
	return 0;
}